/*
 * @Author: yupeigen
 * @Date: 2021-05-12 14:46:03
 * @LastEditTime: 2021-05-12 15:41:49
 * @LastEditors: Please set LastEditors
 * @Description: 文件处理类
 * @FilePath: \sino-vant\src\api\modules\fileUtils.js
 */
import Vue from 'vue'
export default {
    dataURLtoFile (dataurl, filename) { // 将base64转换为file文件
        let arr = dataurl.split(',')
        let mime = arr[0].match(/:(.*?);/)[1]
        let bstr = atob(arr[1])
        let n = bstr.length
        let u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        let file = new File([u8arr], filename, {type: mime})
        const data = { //拼成你所需要传给后端的格式
          file:file,
          content:dataurl,
          message:'',
          status:''
        }
        return data
      },
      compress(file){
             let canvas = document.createElement('canvas') // 创建Canvas对象(画布)
		     let context = canvas.getContext('2d')
             let img = new Image();
             img.src = file.content;
            //  console.log(file.file.size);
            //  console.log(img)
             img.onload = () =>{  //按照比例
                let width = 2000
                let height = width / (img.naturalWidth / img.naturalHeight)
                canvas.width = width 
                canvas.height = height
                context.drawImage(img, 0, 0, canvas.width, canvas.height)
                file.content = canvas.toDataURL(file.file.type, 0.92) // 0.92为默认压缩质量
                let files = this.dataURLtoFile(file.content, file.file.name)
                
                // this.fileList.push(files);
                return files
            }
            
      },
}